﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Input.Touch;

namespace SteelDrum
{
    public partial class GamePage : PhoneApplicationPage
    {
        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;

        SoundEffect steeldrum;
        List<SoundEffectInstance> instances;

        Texture2D bg;

        List<Zone> zones;

        UIElementRenderer elementRenderer;

        float halfstep = 1.0f / 12.0f;

        private class Zone
        {
            Vector2 position;
            float radius;
            public float freq;

            public Zone(Vector2 position, float radius, float freq)
            {
                this.position = position;
                this.radius = radius;
                this.freq = freq;
            }

            public bool Contains(Vector2 spot)
            {
                return (Vector2.Distance(spot, position) <= radius);
            }
        }

        public GamePage()
        {
            InitializeComponent();

            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;

            zones = new List<Zone>();
            zones.Add(new Zone(new Vector2(242, 415), 80, halfstep * 9)); //A
            zones.Add(new Zone(new Vector2(79, 567), 80, halfstep * 4)); //E
            zones.Add(new Zone(new Vector2(242, 570), 80, halfstep * 0)); //C
            zones.Add(new Zone(new Vector2(397, 568), 80, halfstep * 2)); //D
            zones.Add(new Zone(new Vector2(242, 721), 80, halfstep * 7)); //G

            LayoutUpdated += new EventHandler(XNARendering_LayoutUpdated);
        }

        void XNARendering_LayoutUpdated(object sender, EventArgs e)
        {
            // make sure page size is valid
            if (ActualWidth == 0 || ActualHeight == 0)
                return;

            // see if we already have the right sized renderer
            if (elementRenderer != null &&
                elementRenderer.Texture != null &&
                elementRenderer.Texture.Width == (int)ActualWidth &&
                elementRenderer.Texture.Height == (int)ActualHeight)
            {
                return;
            }

            // dispose the current renderer
            if (elementRenderer != null)
                elementRenderer.Dispose();

            // create the renderer
            elementRenderer = new UIElementRenderer(this, (int)ActualWidth, (int)ActualHeight);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            steeldrum = contentManager.Load<SoundEffect>("steeldrum");

            bg = contentManager.Load<Texture2D>("drum");

            // Start the timer
            timer.Start();

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            TouchCollection input = TouchPanel.GetState();

            foreach (TouchLocation loc in input)
            {
                if (loc.State == TouchLocationState.Pressed)
                {
                    foreach (Zone z in zones)
                    {
                        if (z.Contains(loc.Position))
                            steeldrum.Play(1.0f, z.freq, 0.0f);
                    }
                }
            }
        }

        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();
            spriteBatch.Draw(
                bg,
                Vector2.Zero,
                Color.White);
            elementRenderer.Render();
            spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);
            spriteBatch.End();
        }
    }
}